<?php

class sqlfun
{
    public $pdo = '';
    public $dbName = '';

    public function __construct()
    {
        $this->config = $this->getConfig();
        $dbms = $this->config['type'];     //数据库类型
        $host = $this->config['hostname']; //数据库主机名
        $this->dbName = $this->config['database'];    //使用的数据库
        $this->pdo = new PDO("$dbms:host=$host;dbname=$this->dbName", $this->config['username'], $this->config['password']);
    }

    public function getConfig(){
        return include service('DOCUMENT_ROOT') . '/data/conf/database.php';
    }

    public function getPdo()
    {
        return $this->pdo;
    }

    /**
     * 检测数据表是否存在
     * @param string $table
     * @return bool
     */
    public function checkTableExist($table = '')
    {
        $tableName = $table ? $table : self::getTable();
        $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $this->dbName, $this->config['prefix'] . $tableName);
        $result = $this->pdo->query($sql);
        if ($result === false) {//表不存在
            return false;
        }
        if (!$result->fetchColumn(0)) {
            return false;
        }
        return true;
    }

    /**
     * 查找数据
     * @param string $table
     * @param string $where
     * @param string $orderStr
     * @param string $filed
     * @return array
     */
    public function selectAll($table = '', $where = '', $orderStr = '', $filed = '')
    {
        $filed = empty($filed) ? '*' : $this->handFiled($filed);
        $orderStr = empty($orderStr) ? '' : ' ORDER BY ' . $orderStr;
        $where && $where = " WHERE " . $where;

        $sql = sprintf("SELECT %s FROM `%s` %s %s ", $filed, $this->config['prefix'] . $table, $where, $orderStr);
        $result = $this->pdo->query($sql);
        if (false === $result) {
            $this->writeSql($sql);
            return [];
        }
        return $result->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * 处理查询参数
     * @param string $filed
     * @return string
     */
    public function handFiled($filed = '')
    {
        $fileds = explode(',', $filed);
        return '`' . join('`,`', $fileds) . '`';
    }

    public function insert($sql = '') {
        $result = $this->pdo->exec($sql);
        if (false === $result) {
            return false;
        }
        return $this->pdo->lastInsertId();
    }

    public function update($sql = '') {
        $result = $this->pdo->exec($sql);
        if (false === $result) {
            return false;
        }
        return $result;
    }
    public function getOne($sql = '') {
        $result = $this->pdo->query($sql);
        if (false === $result) {
            return [];
        }
        return $result->fetch(PDO::FETCH_ASSOC);
    }

    public function select($sql = '') {
        $result = $this->pdo->query($sql);
        if (false === $result) {
            return [];
        }
        return $result->fetchAll(PDO::FETCH_ASSOC);
    }

    public function selectNum($sql = '') {
        $resultTotal = $this->pdo->query($sql);
        if (false === $resultTotal) {
            return 0;
        } elseif (0 == ($totalNum = $resultTotal->fetchColumn(0))) {
            return 0;
        }
        return $totalNum;
    }

    /**
     * 写入错误sql
     */
    public function writeSql($content)
    {
        $file = $_SERVER['DOCUMENT_ROOT'] . "/runtime/log/sql.log";
        file_put_contents($file, "\r\n********************** " . date('Y-m-d H:i:s', time()) . " **********************************\r\n", FILE_APPEND);
        file_put_contents($file, $content, FILE_APPEND);
    }

}